package com.dove.tinkerpatch;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.tencent.tinker.lib.service.DefaultTinkerResultService;
import com.tencent.tinker.lib.service.PatchResult;
import com.tencent.tinker.lib.util.TinkerLog;
import com.tencent.tinker.lib.util.TinkerServiceInternals;

import java.io.File;

public class MyDefaultTinkerResultService extends DefaultTinkerResultService {
    private static final String TAG = "king_mdtrs";
    @Override
    public void onPatchResult(PatchResult result) {
        if (result == null) {
            TinkerLog.e(TAG, "DefaultTinkerResultService received null result!!!!");
            return;
        }
        TinkerLog.i(TAG, "DefaultTinkerResultService received a result:%s ", result.toString());
        TinkerLog.i(TAG,"关闭接收进程------");
        TinkerServiceInternals.killTinkerPatchServiceProcess(getApplicationContext());
        if (result.isSuccess) {
            deleteRawPatchFile(new File(result.rawPatchFilePath));
            if (checkIfNeedKill(result)) {
                try{
                    TinkerLog.i(TAG,"发现新补丁，自动重启------");
                    jumpToNext(getApplicationContext());
                }catch (Exception e){
                    e.getStackTrace();
                }
            } else {
                TinkerLog.i(TAG, "I have already install the newly patch version!");
                TinkerLog.i(TAG,"不中结进程------");
            }
        }
//        super.onPatchResult(result);
    }

    /**
     * 二次启动
     */
    private void jumpToNext(Context getApplicationContext) {
        TinkerLog.i(TAG,"跳转二次启动------");
//        ActivityManager manager = (ActivityManager)getApplicationContext.getSystemService(Context.ACTIVITY_SERVICE);
//        manager.restartPackage(getApplicationContext.getPackageName());
        restartApplication();
        TinkerLog.i(TAG,"关闭进程------");
        android.os.Process.killProcess(android.os.Process.myPid());

//        Intent intent= new Intent(Intent.ACTION_MAIN);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用，必须加入new task标识
//        intent.addCategory(Intent.CATEGORY_HOME);
//        startActivity(intent);
    }

    private void restartApplication() {
        final Intent intent = getPackageManager().
                getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

}
